<template>
  <div class="department-container">
    <div class="app-container">
      <el-card>
        <!-- 用一个行列布局 -->
        <el-row type="flex" justify="space-between" align="middle" style="height: 40px">
          <el-col :span="20">
            <span>江苏传智播客教育科技股份有限公司</span>
          </el-col>
          <el-col :span="4">
            <el-row type="flex" justify="end">
              <!-- 两个内容 -->
              <el-col>负责人</el-col>
              <el-col>操作</el-col>
            </el-row>
          </el-col>
        </el-row>

        <!-- 放置一个el-tree组件 -->
        <el-tree
          :data="list"
          :props="defaultProps"
          :default-expand-all="true"
        >
          <template #default="{data}">
            <el-row
              type="flex"
              justify="space-between"
              align="middle"
              style="height: 40px; width: 100%;"
            >
              <el-col :span="20">
                <span>{{ data.name }}</span>
              </el-col>
              <el-col :span="4">
                <el-row type="flex" justify="end">
                  <!-- 两个内容 -->
                  <el-col>{{ data.manager }}</el-col>
                  <el-col>
                    <!-- 下拉菜单 element -->
                    <el-dropdown>
                      <span> 操作<i class="el-icon-arrow-down" /> </span>
                      <el-dropdown-menu slot="dropdown">
                        <el-dropdown-item @click.native="AddDialog(data.id)">添加子部门</el-dropdown-item>
                        <el-dropdown-item @click.native="editDialog(data.id)">编辑部门</el-dropdown-item>
                        <el-dropdown-item @click.native="deleteDialog(data.id)">删除部门</el-dropdown-item>
                      </el-dropdown-menu>
                    </el-dropdown>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-tree>
      </el-card>
    </div>

    <!-- 新增部门弹出层 -->
    <el-dialog
      title="提示"
      :visible="addVisible"
      width="30%"
      @close="closeAddDialog"
      @open="openAddDialog"
    >
      <el-form ref="addForm" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="部门名称" prop="name">
          <el-input v-model="form.name" style="width:80%" placeholder="1-50个字符" />
        </el-form-item>
        <el-form-item label="部门编码" prop="code">
          <el-input v-model="form.code" style="width:80%" placeholder="1-50个字符" />
        </el-form-item>
        <el-form-item label="部门负责人" prop="manager">
          <el-select v-model="form.manager" style="width:80%" placeholder="请选择">
            <el-option
              v-for="item in managerList"
              :key="item.id"
              :value="item.username"
              :label="item.username"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="部门介绍" prop="introduce">
          <el-input v-model="form.introduce" style="width:80%" placeholder="1-300个字符" type="textarea" :rows="3" />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button type="primary" size="small" @click="submit">确定</el-button>
        <el-button size="small" @click="cancle">取消</el-button>
      </template>
    </el-dialog>

  </div>
</template>
<script>
import { getDepartments, getEmployeeSimple, getDepartDetail, addDepartments, updateDepartments, delDepartments } from '@/api/department'
import transTree from '@/utils/transTree'
export default {
  data() {
    const validateCode = (rule, value, callback) => {
      let arr = []
      if (this.form.id) {
        arr = this.codeList.filter(item => item.code !== this.catchCode).map(item => item.code)
      }
      arr.includes(value) ? callback(new Error('code编码不能重复')) : callback()
    }
    return {
      list: [],
      // 自定义配置名称
      defaultProps: {
        label: 'name',
        children: 'children'
      },
      addVisible: false,
      form: {
        name: '', // 部门名称
        code: '', // 部门编码
        manager: '', // 部门管理者
        introduce: '', // 部门介绍
        pid: ''// 要添加给哪个父级
      },
      rules: {
        name: [
          { required: true, message: '部门名称不能为空', trigger: ['blur', 'change'] },
          { min: 1, max: 50, message: '部门名称要求1-50个字符', trigger: ['blur', 'change'] }
        ],
        code: [
          { required: true, message: '部门编码不能为空', trigger: ['blur', 'change'] },
          { min: 1, max: 50, message: '部门编码要求1-50个字符', trigger: ['blur', 'change'] },
          { validator: validateCode, trigger: 'blur', message: '部门编码不能重复' }
        ],
        manager: [
          { required: true, message: '部门负责人不能为空', trigger: ['blur', 'change'] }
        ],
        introduce: [
          { required: true, message: '部门介绍不能为空', trigger: ['blur', 'change'] },
          { min: 1, max: 300, message: '部门介绍要求1-300个字符', trigger: ['blur', 'change'] }
        ]
      },
      managerList: [],

      // code校验数据
      catchCode: null,
      codeList: []
    }
  },
  mounted() {
    this.fetchDepartment()
  },
  methods: {
    async fetchDepartment() {
      const res = await getDepartments()
      // this.list = res.depts
      // 将平铺数据转换为树形结构数据
      this.list = transTree(res.depts)
      this.codeList = res.depts
    },
    // 打开弹框
    AddDialog(id) {
      this.addVisible = true
      this.form.pid = id
    },
    // 关闭弹框
    closeAddDialog() {
      this.addVisible = false
      // 清除校验痕迹
      this.$refs.addForm.resetFields()
      this.resetForm()
    },
    async openAddDialog() {
      const res = await getEmployeeSimple()
      this.managerList = res
    },
    cancle() {
      this.addVisible = false
      this.resetForm()
    },
    resetForm() {
      // 清空表单内容
      this.form = {
        name: '', // 部门名称
        code: '', // 部门编码
        manager: '', // 部门管理者
        introduce: '', // 部门介绍
        pid: ''// 要添加给哪个父级
      }
    },
    submit() {
      this.$refs.addForm.validate(async valid => {
        if (valid) {
          if (this.form.id) {
            await updateDepartments(this.form)
          } else {
            await addDepartments(this.form)
          }

          this.$message.success(`${this.form.id ? '修改' : '添加'}节点成功`)
          this.fetchDepartment()
          this.closeAddDialog()
        }
      })
    },
    async editDialog(id) {
      this.addVisible = true
      const res = await getDepartDetail(id)
      this.form = res
      // 当前正在编辑的部门编码
      this.catchCode = res.code
    },
    deleteDialog(id) {
      this.$confirm('确定要删除该节点吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await delDepartments(id)
        this.fetchDepartment()
        this.$message.success('删除成功')
      }).catch(() => {
        this.$message.error('删除失败')
      })
    }
  }
}
</script>
